package top.atcra.rpc.transport.message;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.Getter;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 请求头结构 <br>
 * <p>
 * * 3B magic(协议标识) <br>
 * * 1B version(版本)   <br>
 * * 2B header length 首部的长度 <br>
 * * 4B full length 报文总长度 <br>
 * * 1B serializeType <br>
 * * 1B compressType <br>
 * * 8B requestId <br>
 * * 8B timestamp
 * * 1B requestType <br>
 *
 * @author atcra
 * @date 2025-3-23
 */
@Data
@Builder
public class RPCRequest {
    private static final byte[] protocolIdentifier = "cra".getBytes(StandardCharsets.UTF_8);
    private byte version;
    private byte requestType;// 请求类型
    private byte serializeType; // 序列化类型
    private byte compressType; // 压缩类型
    private long requestId;
    private long timestamp;
    private int headerLength;
    private int bodyLength;
    private RequestPayload body;

    @Getter
    @AllArgsConstructor
    public enum RequestType {
        NORMAL((byte) 0),
        HEALTH_DETECT((byte) 1);
        private final byte id;
        private static final Map<Byte, RequestType> map = new HashMap<>();

        static {
            for (RequestType type : RequestType.values()) {
                map.put(type.id, type);
            }
        }

        public static RequestType valueOf(byte id) {
            return map.get(id);
        }
    }


    public ByteBuf toByteBuf() {
        ByteBuf buf = Unpooled.buffer();
        buf.writeBytes(protocolIdentifier);
        buf.writeByte(version);
        buf.writeByte(requestType);
        buf.writeByte(serializeType);
        buf.writeByte(compressType);
        buf.writeLong(requestId);
        buf.writeInt(headerLength);
        buf.writeInt(bodyLength);
        return buf;
    }
}
